package com.hsmpay.mobile.util.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.mobile.action.base.MobileBaseAction;
import com.hsmpay.mobile.action.user.UserAction;
import com.hsmpay.mobile.service.user.UserService;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import java.util.Map;

public class CheckWeChartLoginInterceptor extends AbstractInterceptor {
    private static final long serialVersionUID = 333596626518725500L;
    static Logger log = Logger.getLogger(CheckWeChartLoginInterceptor.class);

    @Resource(name = "userService")
    protected UserService<User, Long> userService;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        MobileBaseAction action = (MobileBaseAction) invocation.getAction();
        ActionContext act = invocation.getInvocationContext();
        Map<String, Object> sessionMap = null;
        User user = null;
        JSONObject js = null;
        try {
            log.debug("访问URI：###" + action.getRequest().getRequestURL() + "###");
            Long userId = null;

            //判断登录是否 还有效
            sessionMap = act.getSession();
            user = (User) sessionMap.get(UserAction.SESSION_USER);
            if (user == null) {

                log.error("用户会话失效，请重新登录！" + action.getRequest().getSession().getId());
                Cookie[] strArray = action.getRequest().getCookies();
                if (strArray != null) {
                    for (Cookie cookie : strArray) {
                        log.error(cookie.getName() + "=" + cookie.getValue());
                    }
                }
                action.sendWeChatErrorMsg("9990");
                return null;
            } else {//判断是否过期
                if (userService.isOldMemcachedUser(user)) {//过期 就是用户被别人挤下去了 使用Memcached
                    sessionMap.remove(UserAction.SESSION_USER);//清除会话中的用户
                    log.error("对不起，您的帐号[" + user.getLoginName() + "]已在别的地方登录，您已经被迫退出。若有疑问请联系管理员，谢谢！");
                    action.sendWeChatErrorMsg("9991", user.getLoginName());
                    return null;
                }
            }

            log.debug("通过过滤器！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            action = null;
            act = null;
            sessionMap = null;
            user = null;
            js = null;
        }
        return invocation.invoke();
    }

}
